<?php

require_once 'Ext/User/Edit/Email/Interface.php';

class Ext_User_Edit_Email_Adapter_Db extends Ext_User_Edit_Email_Abstract
{
    const RECORD_NOT_FOUND        = 'RecordNotFound';
    const EMAIL_FORMAT_ERROR      = 'emailFormatError';
    const EMAIL_ALREADY_EXISTS    = 'emailAlreadyExists';
    const UNCATEGORIZED           = 'uncategorized';
    protected $_messageTemplates = array(
        self::RECORD_NOT_FOUND       => "Record not found.",
        self::EMAIL_FORMAT_ERROR     => "Email format error.",
        self::EMAIL_ALREADY_EXISTS   => "Email '%email%' already exists.",
        self::UNCATEGORIZED          => "Uncategorized.",
    );
    
    public function edit($email)
    {
        $result = array(
            'code'        => Ext_User_Edit_Email_Result::FAILURE,
            'messages'    => array(),
        );
        
        $userProfile = App_Model_DbTable_User_Profile::getInstance()->getRowByUserId($this->_userId);
        if(!$userProfile)
        {
            $result['messages'][] = $this->_messager->createMessage(self::RECORD_NOT_FOUND);
            return new Ext_User_Edit_Email_Result($result['code'], $result['messages']);
        }
        $oldEmail = $userProfile['email'];
        
        $em = new Zend_Validate_EmailAddress();
        if(!$em->isValid($email)){
            $result['messages'][] = $this->_messager->createMessage(self::EMAIL_FORMAT_ERROR);
            return new Ext_User_Edit_Email_Result($result['code'], $result['messages']);
        }
        
        $userAccountBaseEmail = App_Model_DbTable_User_Account_Base_Email::getInstance()->getRowByEmail($email);
        if($userAccountBaseEmail){
            if($userAccountBaseEmail['status']){
                if($userAccountBaseEmail['userId'] != $this->_userId){
                    $result['messages'][] = $this->_messager->createMessage(self::EMAIL_ALREADY_EXISTS, array('email'=>$email));
                    return new Ext_User_Edit_Email_Result($result['code'], $result['messages']);
                }
            }
        }
        
        $row = array(
            'status' => 0,
        );
        App_Model_DbTable_User_Account_Base_Email::getInstance()->addOld($row, $oldEmail);
        
        if($userAccountBaseEmail){
            $row = array(
                'userId' => $this->_userId,
                'status' => 1,
            );
            App_Model_DbTable_User_Account_Base_Email::getInstance()->addOld($row, $email);
        }else{
            $row = array(
                'email'  => $email,
                'userId' => $this->_userId,
                'status' => 1,
            );
            App_Model_DbTable_User_Account_Base_Email::getInstance()->addNew($row);
        }
    
        $result['code'] = Ext_User_Edit_Email_Result::SUCCESS;
        return new Ext_User_Edit_Email_Result($result['code'], $result['messages']);

    }

}
